﻿Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging

Namespace Utilities
    Public Class ImageUtil
        Private _Lx As Integer
        Private _Ly As Integer
        Private _X As Integer
        Private _Y As Integer
        Private _Path As String
        Private _UserName As String
        Private _Copyright As String
        Private _UploadType As String
        Private _stream As Stream
        Private _FileName As String

        Public Property X() As Integer
            Get
                Return _X
            End Get
            Set(ByVal value As Integer)
                _X = value
            End Set
        End Property

        Public Property Y() As Integer
            Get
                Return _Y
            End Get
            Set(ByVal value As Integer)
                _Y = value
            End Set
        End Property

        Public Property FileName() As String
            Get
                Return _FileName
            End Get
            Set(ByVal value As String)
                _FileName = value
            End Set
        End Property

        Public Property UserName() As String
            Get
                Return _UserName
            End Get
            Set(ByVal value As String)
                _UserName = value
            End Set
        End Property

        Public Property Copyright() As String
            Get
                Return _Copyright
            End Get
            Set(ByVal value As String)
                _Copyright = value
            End Set
        End Property

        Public Property Path() As String
            Get
                Return _Path
            End Get
            Set(ByVal value As String)
                _Path = value
            End Set
        End Property

        Public Property Lx() As Integer
            Get
                Return _Lx
            End Get
            Set(ByVal value As Integer)
                _Lx = value
            End Set
        End Property

        Public Property Ly() As Integer
            Get
                Return _Ly
            End Get
            Set(ByVal value As Integer)
                _Ly = value
            End Set
        End Property

        Public Property stream() As Stream
            Get
                Return _stream
            End Get
            Set(ByVal value As Stream)
                _stream = value
            End Set
        End Property

        Public Property UploadType() As String
            Get
                Return _UploadType
            End Get
            Set(ByVal value As String)
                _UploadType = value
            End Set
        End Property

        Public Sub New(ByVal stream As Stream, ByVal Lx As Integer, ByVal Ly As Integer, ByVal UploadType As String, ByVal UserName As String, ByVal FileName As String)
            Me.stream = stream
            Me.Lx = Lx
            Me.Ly = Ly
            Me.UploadType = UploadType
            Me.UserName = UserName
            Me.FileName = FileName
        End Sub

        Public Sub New(ByVal Path As String, ByVal Lx As Integer, ByVal Ly As Integer, ByVal UploadType As String, ByVal UserName As String, ByVal FileName As String)
            Me.Path = Path
            Me.Lx = Lx
            Me.Ly = Ly
            Me.UploadType = UploadType
            Me.UserName = UserName
            Me.FileName = FileName
        End Sub

        Public Sub New(ByVal Path As String, ByVal Lx As Integer, ByVal Ly As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal UploadType As String, ByVal UserName As String, ByVal FileName As String)
            Me.Path = Path
            Me.Lx = Lx
            Me.Ly = Ly
            Me.X = X
            Me.Y = Y
            Me.UploadType = UploadType
            Me.UserName = UserName
            Me.FileName = FileName
        End Sub

        Public Function CropImage() As Boolean
            Try
                Dim originalimg As Image

                If Path = "" Then
                    originalimg = Image.FromStream(stream)
                Else
                    Path = Configs.UserFolder & Path.Replace("/Files/", "").Replace("/", "\")
                    If File.Exists(Path) Then
                        originalimg = Image.FromFile(Path)
                        '/JustinSLR/avatar/JustinSLR_avatar__20100410002144IzYp.jpg
                    Else
                        'originalimg = Image.FromFile(Configs.UserFolder & "no_image_s.gif")
                        Return False
                    End If
                End If

                'If Lx > 150 Then
                '    Lx = 150
                '    Ly = 150
                'End If

                Dim thumb As New Bitmap(Lx, Ly)
                Dim gr_dest As Graphics = Graphics.FromImage(thumb)
                Dim sb = New SolidBrush(Color.White)

                gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height)
                gr_dest.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
                gr_dest.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                gr_dest.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
                'gr_dest.DrawImage(originalimg, X, Y, thumb.Width, thumb.Height)
                gr_dest.DrawImage(originalimg, New Rectangle(0, 0, thumb.Width, thumb.Height), X, Y, thumb.Width, thumb.Height, GraphicsUnit.Pixel)

                gr_dest.Save()

                If UploadType = "Avatar" Then
                    Dim strFolderAvatar As String = Configs.UserFolder & UserName & "\avatar\"
                    If Not Directory.Exists(strFolderAvatar) Then
                        Directory.CreateDirectory(strFolderAvatar)
                    End If
                    thumb.Save(strFolderAvatar & FileName, Imaging.ImageFormat.Jpeg)
                ElseIf UploadType = "CropImage" Then

                End If

                If Not thumb Is Nothing Then
                    thumb.Dispose()
                    thumb = Nothing
                End If

                If Not originalimg Is Nothing Then
                    originalimg.Dispose()
                    originalimg = Nothing
                End If
                Return True
            Catch ex As Exception
                Return False
            End Try
        End Function

        Public Function OriImageFixSize() As Boolean
            Try
                Dim bFlag As Boolean = False
                Dim NewWidth As Integer = 0
                Dim NewHeight As Integer = 0
                Dim originalimg As Image

                If Path = "" Then
                    originalimg = Image.FromStream(stream)
                Else
                    If File.Exists(Path) Then
                        Path = Configs.UserFolder & Path.Replace("/Files/", "").Replace("/", "\")
                        originalimg = Image.FromFile(Path)
                    Else
                        originalimg = Image.FromFile(Configs.UserFolder & "no_image_s.gif")
                    End If
                End If

                If originalimg.Width > Lx Then
                    bFlag = False
                Else
                    bFlag = True
                End If

                If bFlag Then
                    NewHeight = originalimg.Height
                    NewWidth = originalimg.Width

                    Dim strFolderAvatar As String = Configs.UserFolder & UserName & "\avatar\"
                    If Not Directory.Exists(strFolderAvatar) Then
                        Directory.CreateDirectory(strFolderAvatar)
                    End If
                    originalimg.Save(strFolderAvatar & FileName, Imaging.ImageFormat.Jpeg)

                    If Not originalimg Is Nothing Then
                        originalimg.Dispose()
                        originalimg = Nothing
                    End If

                    bFlag = True
                Else
                    bFlag = False
                End If

                Return bFlag
            Catch ex As Exception
                Return False
            End Try
        End Function

        Public Function ResizeImage() As Boolean
            Try
                Dim i As Integer
                Dim NewWidth As Integer = 0
                Dim NewHeight As Integer = 0
                Dim originalimg As Image

                If Path = "" Then
                    originalimg = Image.FromStream(stream)
                Else
                    If File.Exists(Path) Then
                        Path = Configs.UserFolder & Path.Replace("/Files/", "").Replace("/", "\")
                        originalimg = Image.FromFile(Path)
                    Else
                        originalimg = Image.FromFile(Configs.UserFolder & "no_image_s.gif")
                    End If
                End If

                If originalimg.Width < Lx Or originalimg.Height < Ly Then
                    NewHeight = originalimg.Height - ((originalimg.Height * 15) / 100)
                    NewWidth = originalimg.Width - ((originalimg.Width * 15) / 100)
                    i = 1
                Else
                    NewHeight = Ly
                    NewWidth = Lx
                    i = 0
                End If

                Dim thumb As New Bitmap(NewWidth, NewHeight)
                Dim gr_dest As Graphics = Graphics.FromImage(thumb)
                Dim sb = New SolidBrush(Color.White)
                gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height)
                gr_dest.DrawImage(originalimg, 0, 0, thumb.Width, thumb.Height)
                gr_dest.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                gr_dest.InterpolationMode = Drawing2D.InterpolationMode.High
                If Not Copyright = "" Then
                    gr_dest.DrawString(Copyright, New Font("Arial", 10), New SolidBrush(Color.Blue), (thumb.Width * 60) / 100, (thumb.Height * 1) / 100)
                End If

                If i = 1 Then
                    gr_dest.Save()
                    If UploadType = "Avatar" Then
                        Dim strFolderAvatar As String = Configs.UserFolder & UserName & "\avatar\"
                        If Not Directory.Exists(strFolderAvatar) Then
                            Directory.CreateDirectory(strFolderAvatar)
                        End If
                        thumb.Save(strFolderAvatar & FileName, Imaging.ImageFormat.Jpeg)
                    Else

                    End If
                Else
                    gr_dest.Save()
                    If UploadType = "Avatar" Then
                        Dim strFolderAvatar As String = Configs.UserFolder & UserName & "\avatar\"
                        If Not Directory.Exists(strFolderAvatar) Then
                            Directory.CreateDirectory(strFolderAvatar)
                        End If
                        thumb.Save(strFolderAvatar & FileName, Imaging.ImageFormat.Jpeg)
                    Else

                    End If
                End If

                If Not thumb Is Nothing Then
                    thumb.Dispose()
                End If

                If Not originalimg Is Nothing Then
                    originalimg.Dispose()
                End If
                Return True
            Catch ex As Exception
                Return False
            End Try
        End Function

        Public Function PublicUpload(ByVal Lx As Integer, ByVal Ly As Integer, ByVal _FileName As String, ByVal CopyRight As String) As String
            Me.Lx = Lx
            Me.Ly = Ly
            Me.FileName = Lx.ToString & "x" & Ly.ToString & "__" & _FileName
            Return PublicUpload(CopyRight)
        End Function

        Public Function PublicUpload(ByVal Copyright As String) As String
            Try
                Dim strMsg As String = ""
                Me.Copyright = Copyright
                Dim i As Integer
                Dim NewWidth As Integer = 0
                Dim NewHeight As Integer = 0
                Dim originalimg As Image
                Dim strPhyPath As String = Configuration.ConfigurationManager.AppSettings("UserFolder").ToString

                If Path = "" Then
                    originalimg = Image.FromStream(stream)
                Else
                    If File.Exists(Path) Then
                        Path = Configs.UserFolder & Path.Replace("/Files/", "").Replace("/", "\")
                        originalimg = Image.FromFile(Path)
                    Else
                        originalimg = Image.FromFile(Configs.UserFolder & "no_image_s.gif")
                    End If
                End If

                If originalimg.Width <= Lx Then
                    NewWidth = originalimg.Width
                    NewHeight = originalimg.Height
                    i = 1
                Else
                    Dim dAspect As Double = originalimg.Height / originalimg.Width
                    NewWidth = Lx
                    NewHeight = Convert.ToInt32(Math.Round(Lx * dAspect))

                    i = 0
                End If

                Dim thumb As New Bitmap(NewWidth, NewHeight)
                Dim gr_dest As Graphics = Graphics.FromImage(thumb)
                Dim sb = New SolidBrush(Color.White)
                gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height)
                gr_dest.DrawImage(originalimg, 0, 0, thumb.Width, thumb.Height)

                If NewWidth = 160 And NewHeight > 120 Then
                    strMsg = "Crop"
                Else
                    strMsg = "OK"
                End If

                'set quality for image
                gr_dest.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
                gr_dest.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
                'new add
                gr_dest.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                gr_dest.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                'end set

                'write copyright text on image
                If Not Copyright = "" Then
                    gr_dest.DrawString(Copyright, New Font("Verdana", 10), New SolidBrush(Color.Blue), NewWidth - 235, NewHeight - 17)
                End If

                Dim codecEncoder As ImageCodecInfo = GetEncoder("image/jpeg")
                Const quality As Integer = 90
                Dim encodeParams As New EncoderParameters(1)
                Dim qualityParam As New EncoderParameter(Encoder.Quality, quality)
                encodeParams.Param(0) = qualityParam

                Dim strFolderUpload As String = strPhyPath & UserName & "\" & DateTime.Now.Year.ToString & "\" & Right("0" & DateTime.Now.Month.ToString, 2) & "\" & Right("0" & DateTime.Now.Day.ToString, 2) & "\"
                If Not Directory.Exists(strFolderUpload) Then
                    Directory.CreateDirectory(strFolderUpload)
                End If

                If i = 1 Then
                    gr_dest.Save()
                    If UploadType = "UploadService" Then
                        thumb.Save(strFolderUpload & FileName, codecEncoder, encodeParams)
                    End If
                Else
                    gr_dest.Save()
                    If UploadType = "UploadService" Then
                        thumb.Save(strFolderUpload & FileName, codecEncoder, encodeParams)
                    End If
                End If

                If Not thumb Is Nothing Then
                    thumb.Dispose()
                End If

                If Not originalimg Is Nothing Then
                    originalimg.Dispose()
                End If

                Return strMsg
            Catch ex As Exception
                Return ex.Message
            End Try
        End Function

        Function GetEncoder(ByVal mimeType As String) As ImageCodecInfo
            Dim codecs() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders()
            For Each codec As ImageCodecInfo In codecs
                If codec.MimeType = mimeType Then
                    Return codec
                End If
            Next
        End Function
    End Class
End Namespace